package com.hzlh.filter;

import com.hzlh.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 跨域设置
 */
@Slf4j
public class CorsFilter implements Filter {
    private List<String> allowOrigins;

    private String profiles;

    public CorsFilter(String allowOrgin, String profiles) {
        LOGGER.info("CorsFilter-- start"+System.currentTimeMillis());
        if (!StringUtils.isEmpty(allowOrgin)) {
            String[] origins = allowOrgin.split(",");
            this.allowOrigins = Stream.of(origins).collect(Collectors.toList());
            this.profiles = profiles;
        } else {
            LOGGER.warn("未配置允许跨域的站点，将使用默认设置");
            this.allowOrigins = new ArrayList<>();
        }
        LOGGER.info("CorsFilter-- end"+System.currentTimeMillis());
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //String refer = (String) request.getHeader("Referer");
        // 考虑Referer安全性问题，采用Origin请求头
        String origin = request.getHeader("Origin");
//        LOGGER.info("doFilter---origin="+origin);
        if (allowOrigins.contains(origin) || "dev".equals(profiles)) {
            response.addHeader("Access-Control-Allow-Origin", origin);
        } else {
            response.addHeader("Access-Control-Allow-Origin", "https://entry.linker.cc");
        }
        response.addHeader("Access-Control-Allow-Credentials", "true");
        response.addHeader("Access-Control-Max-Age", "30");
        response.addHeader("Access-Control-Allow-Methods", "OPTIONS,GET,POST,DELETE");
        response.addHeader("Access-Control-Allow-Headers",
                "Origin, X-Requested-With, Content-Type, Accept, lang, " + Constants.H5_TOKEN_NAME+", "+Constants.PC_TOKEN);
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
